"""
工作流编排器
提供专门的工作流编排和管理功能，增强工作流执行的可视化和调试能力
"""

import asyncio
import logging
from typing import Dict, Any, List, Optional, Callable, Union, Awaitable
from dataclasses import dataclass
from datetime import datetime
import json

from src.research_core.workflow_manager import get_workflow_manager, WorkflowManager
from src.research_core.workflow_registry import get_workflow_registry

logger = logging.getLogger(__name__)

@dataclass
class WorkflowExecutionEvent:
    """工作流执行事件"""
    event_type: str
    timestamp: datetime
    workflow_name: str
    data: Dict[str, Any]
    execution_id: str

class WorkflowOrchestrator:
    """工作流编排器，提供高级工作流管理和编排功能"""
    
    def __init__(self):
        self.workflow_manager: WorkflowManager = get_workflow_manager()
        self.event_handlers: Dict[str, List[Callable]] = {}
        self.execution_history: List[WorkflowExecutionEvent] = []
        self.max_history_size = 1000
        
    def register_event_handler(self, event_type: str, handler: Callable) -> None:
        """
        注册事件处理器
        
        Args:
            event_type: 事件类型
            handler: 事件处理器函数
        """
        if event_type not in self.event_handlers:
            self.event_handlers[event_type] = []
        self.event_handlers[event_type].append(handler)
    
    async def emit_event(self, event: WorkflowExecutionEvent) -> None:
        """
        发出事件
        
        Args:
            event: 工作流执行事件
        """
        # 添加到历史记录
        self.execution_history.append(event)
        if len(self.execution_history) > self.max_history_size:
            self.execution_history = self.execution_history[-self.max_history_size:]
        
        # 调用事件处理器
        handlers = self.event_handlers.get(event.event_type, [])
        for handler in handlers:
            try:
                if asyncio.iscoroutinefunction(handler):
                    await handler(event)
                else:
                    handler(event)
            except Exception as e:
                logger.error(f"事件处理器执行失败: {e}")
    
    async def execute_workflow(
        self, 
        workflow_name: str, 
        inputs: Dict[str, Any],
        timeout: int = 300,
        max_iterations: int = 10,
        version: str = "latest",
        callback: Optional[Callable[[Dict[str, Any]], Union[None, Awaitable[None]]]] = None
    ) -> Dict[str, Any]:
        """
        执行工作流
        
        Args:
            workflow_name: 工作流名称
            inputs: 输入数据
            timeout: 超时时间（秒）
            max_iterations: 最大迭代次数
            version: 工作流版本
            callback: 执行完成后的回调函数
            
        Returns:
            工作流执行结果
        """
        execution_id = f"{workflow_name}_{datetime.now().strftime('%Y%m%d_%H%M%S_%f')}"
        
        # 发出开始事件
        await self.emit_event(WorkflowExecutionEvent(
            event_type="workflow_start",
            timestamp=datetime.now(),
            workflow_name=workflow_name,
            data={
                "inputs": inputs,
                "timeout": timeout,
                "max_iterations": max_iterations,
                "version": version
            },
            execution_id=execution_id
        ))
        
        try:
            # 执行工作流
            result = await self.workflow_manager.execute_workflow(
                workflow_name=workflow_name,
                inputs=inputs,
                timeout=timeout,
                max_iterations=max_iterations
            )
            
            # 发出成功事件
            await self.emit_event(WorkflowExecutionEvent(
                event_type="workflow_success",
                timestamp=datetime.now(),
                workflow_name=workflow_name,
                data={
                    "result": result
                },
                execution_id=execution_id
            ))
            
            # 调用回调函数
            if callback:
                try:
                    if asyncio.iscoroutinefunction(callback):
                        await callback(result)
                    else:
                        callback(result)
                except Exception as e:
                    logger.error(f"回调函数执行失败: {e}")
            
            return result
            
        except Exception as e:
            # 发出失败事件
            await self.emit_event(WorkflowExecutionEvent(
                event_type="workflow_error",
                timestamp=datetime.now(),
                workflow_name=workflow_name,
                data={
                    "error": str(e),
                    "error_type": type(e).__name__
                },
                execution_id=execution_id
            ))
            
            # 重新抛出异常
            raise e
    
    def get_workflow_stats(self) -> Dict[str, Any]:
        """
        获取工作流统计信息
        
        Returns:
            工作流统计信息
        """
        manager_stats = self.workflow_manager.get_metrics()
        performance_stats = self.workflow_manager.get_execution_time_stats()
        
        return {
            "manager_stats": manager_stats,
            "performance_stats": performance_stats,
            "execution_history": len(self.execution_history)
        }
    
    def get_available_workflows(self) -> Dict[str, Dict]:
        """
        获取可用工作流列表
        
        Returns:
            可用工作流信息
        """
        registry = get_workflow_registry()
        return registry.list_workflows()
    
    def get_execution_history(self, limit: int = 50) -> List[Dict[str, Any]]:
        """
        获取执行历史
        
        Args:
            limit: 返回记录数量限制
            
        Returns:
            执行历史记录
        """
        history = self.execution_history[-limit:] if limit < len(self.execution_history) else self.execution_history
        return [
            {
                "event_type": event.event_type,
                "timestamp": event.timestamp.isoformat(),
                "workflow_name": event.workflow_name,
                "execution_id": event.execution_id,
                "data": event.data
            }
            for event in history
        ]

# 全局工作流编排器实例
workflow_orchestrator = WorkflowOrchestrator()

def get_workflow_orchestrator() -> WorkflowOrchestrator:
    """获取工作流编排器实例"""
    return workflow_orchestrator

# 导出
__all__ = ["WorkflowOrchestrator", "workflow_orchestrator", "get_workflow_orchestrator"]